﻿using FRMS.DAL;
using FRMS.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace FRMS.BUS
{
    public class ApplyJLBUS

    {
        public static string controllerLaststate = "";
        public static int workmodeLast = 0;
        public static int sendtime = 0;
        /// <summary>
        /// 控制接口-梯控模式下发
        /// </summary>
        /// <param name="JLdata"></param>
        /// <returns></returns>

        public void LiftModeCMD(ElevatorInfo JLdata)
        {
            ResponseMessage message = new ResponseMessage();
            JLNonstandardData CustomData = new JLNonstandardData();
            ModbusRtu mrtu = new ModbusRtu();
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.ElevatorID = JLdata.ID;
            deviceInfo.DeviceType = 2;
            DeviceDAL da = new DeviceDAL();
            List<DeviceInfo> list = da.QueryDeviceInfo(deviceInfo);
            //根据elevatorid查找deviceid
            try
            {
                foreach (var item in list)
                {
                    if (item.DeviceState=="在线")
                    {
                        JLNonstandardResponse JLNonstandard = new JLNonstandardResponse();
                        JLNonstandard.Name = "customRequest";
                        JLNonstandard.UUID = item.DeviceUuid;
                        JLNonstandard.TimeStamp = GetTimeStamp();
                        JLNonstandard.Session = item.Session;
                        CustomData.CustomData = mrtu.GetLiftStateCmd(JLdata.Workmode);
                        JLNonstandard.Data = CustomData;
                        LogHelper.Log("下发梯控模式" + JsonConvert.SerializeObject(JLNonstandard));
                        string re = HttpClientPost("http://" + item.DeviceIP + ":8011/Request", JLNonstandard);
                        JLNonstandardReturn JLNonstandardReturn = JsonConvert.DeserializeObject<JLNonstandardReturn>(re);
                        if (JLNonstandardReturn.Code == 1)
                        {
                            string name = "";
                            if (JLdata.Workmode == 0)
                            {
                                name = "梯控关闭";
                            }
                            else
                            {
                                name = "梯控开启";
                            }
                            bool rs = SetDoorUI(JLNonstandard, item.DeviceIP, name);
                            //下发梯控模式成功后立刻下发一次查询命令来获取梯控状态
                            bool res = QueryCMD(JLNonstandard, item.DeviceIP);
                        }
                    }
                }
                
            }
            catch (Exception e)
            {
                //message.errcode = 1;
            }
        }

        /// <summary>
        /// 控制接口-梯控模式下发
        /// </summary>
        /// <param name="JLdata"></param>
        /// <returns></returns>

        public bool QueryCMD(JLNonstandardResponse JLdata, string devip)
        {
            Wait(2000);
            LogHelper.Log("查询梯控状态" + JsonConvert.SerializeObject(JLdata));
            ResponseMessage message = new ResponseMessage();
            JLNonstandardData CustomData = new JLNonstandardData();
            ModbusRtu mrtu = new ModbusRtu();
            //DeviceInfo deviceInfo = new DeviceInfo();
            //deviceInfo.ElevatorID = JLdata.ID;
            //deviceInfo.DeviceType = 2;
            //DeviceDAL da = new DeviceDAL();
            //List<DeviceInfo> list = da.QueryDeviceInfo(deviceInfo);
            //根据elevatorid查找deviceid
            try
            {
                JLNonstandardResponse JLNonstandard = new JLNonstandardResponse();
                JLNonstandard.Name = JLdata.Name;// "customRequest";
                JLNonstandard.UUID = JLdata.UUID;// "umph52vvm5mu";
                JLNonstandard.TimeStamp = JLdata.TimeStamp;// 111111;
                JLNonstandard.Session = JLdata.Session;// "umph52vvm5mu_1234567890";
                CustomData.CustomData = mrtu.GetheartbeatToDevices();
                JLNonstandard.Data = CustomData;
                string re = HttpClientPost("http://" + devip + ":8011/Request", JLNonstandard);
                JLNonstandardReturn JLNonstandardReturn = JsonConvert.DeserializeObject<JLNonstandardReturn>(re);
                if (JLNonstandardReturn.Code == 1)
                {
                    //下发梯控模式成功后立刻下发一次查询命令来获取梯控状态
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
            //return message;
        }

        /// <summary>
        /// 心跳数据接口-485心跳数据及发送频率下发
        /// </summary>
        /// <param name="JLdata"></param>
        /// <returns></returns>
        public bool Heartbead485msg(JLRegisterInfo JLdata)
        {
            JLDisplaymsgData Displaymsg = new JLDisplaymsgData();
            JLHeartbead485msgData mrtu = new JLHeartbead485msgData();
            ModbusRtu rdata = new ModbusRtu();
            JLDeviceInfo JL = new JLDeviceInfo();
            JLDeviceDetail JL1 = new JLDeviceDetail();
            try
            {
                JLHeartbead485msgResponse JLDisplaymsg = new JLHeartbead485msgResponse();
                JLDisplaymsg.Name = "heartbeatRequest";
                JLDisplaymsg.UUID = JLdata.UUID;// "umph52vvm5mu";
                JLDisplaymsg.TimeStamp = JLdata.TimeStamp;// 111111;
                JLDisplaymsg.Session = JLdata.UUID + "_" + JLdata.TimeStamp;// "umph52vvm5mu_1234567890";
                mrtu.heartbeatData = rdata.GetheartbeatToDevices();
                mrtu.frequency = 10000;
                JLDisplaymsg.Data = mrtu;
                JL = JLdata.Data;
                JL1 = JL.DeviceInfo;
                string re = HttpClientPost("http://" + JL1.DeviceIP + ":8011/Request", JLDisplaymsg);
                JLNonstandardReturn JLNonstandardReturn = JsonConvert.DeserializeObject<JLNonstandardReturn>(re);
                if (JLNonstandardReturn.Code == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="datajson"></param>
        /// <returns></returns>
        public void comdataRequest(JLCommsgResponse JLCommsg)
        {
            ModbusRtu mrtu = new ModbusRtu();
            string ComData = JLCommsg.Data.ComData;
            byte[] tmp = mrtu.StrToByte(ComData);
            try
            {
                if (tmp[3] == 3)
                {
                    //1、心跳数据
                    DeviceInfo devinfo = new DeviceInfo();
                    DeviceDAL dal = new DeviceDAL();

                    string controllerstateByte = Convert.ToString(tmp[10], 2).PadLeft(8, '0');//40003-bit0-bit7
                    string workmodestateByte = Convert.ToString(tmp[9], 2).PadLeft(8, '0');// 40003-bit8-bit15

                    List<DeviceInfo> list = dal.QueryDeviceInf(JLCommsg.UUID);
                    if (list == null) return;
                    if (list.Count > 0)
                    {
                        if (controllerstateByte.Substring(1, 1) == "1" || controllerstateByte.Substring(0, 1) == "1")//判断C-link或者CAN连接状态
                        {
                            //控制器在线


                            if (controllerLaststate == "")
                            {
                                controllerLaststate = "在线";
                                //更新控制器状态
                                devinfo.ID = list[0].ID;
                                devinfo.DeviceUuid = JLCommsg.UUID;
                                devinfo.ControllerState = controllerLaststate;
                                devinfo.ControllerStateUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                bool result = dal.UpdateControllerState(devinfo);
                                if (result == true)
                                {
                                    //新增日志记录
                                    bool res = dal.AddControllerState(devinfo);
                                }

                            }
                            else
                            {
                                if (controllerLaststate != "在线")
                                {
                                    controllerLaststate = "在线";
                                    //更新控制器状态
                                    devinfo.ID = list[0].ID;
                                    devinfo.DeviceUuid = JLCommsg.UUID;
                                    devinfo.ControllerState = controllerLaststate;
                                    devinfo.ControllerStateUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    bool result = dal.UpdateControllerState(devinfo);
                                    //新增日志记录
                                    if (result == true)
                                    {
                                        //新增日志记录
                                        bool res = dal.AddControllerState(devinfo);
                                    }
                                }
                            }
                        }
                        else
                        {
                            //控制器离线
                            if (controllerLaststate == "")
                            {
                                controllerLaststate = "离线";
                                //更新控制器状态
                                devinfo.ID = list[0].ID;
                                devinfo.DeviceUuid = JLCommsg.UUID;
                                devinfo.ControllerState = controllerLaststate;
                                devinfo.ControllerStateUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                bool result = dal.UpdateControllerState(devinfo);
                                //新增日志记录
                                if (result == true)
                                {
                                    //新增日志记录
                                    bool res = dal.AddControllerState(devinfo);
                                }
                            }
                            else
                            {
                                if (controllerLaststate != "离线")
                                {
                                    controllerLaststate = "离线";
                                    //更新控制器状态
                                    devinfo.ID = list[0].ID;
                                    devinfo.DeviceUuid = JLCommsg.UUID;
                                    devinfo.ControllerState = controllerLaststate;
                                    devinfo.ControllerStateUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                    bool result = dal.UpdateControllerState(devinfo);
                                    //新增日志记录
                                    if (result == true)
                                    {
                                        //新增日志记录
                                        bool res = dal.AddControllerState(devinfo);
                                    }
                                }
                            }
                        }
                        int workmode = int.Parse(workmodestateByte.Substring(7, 1));//当前工作模式

                        if (workmode != workmodeLast)
                        {
                            workmodeLast = workmode;
                            devinfo.ID = list[0].ID;
                            devinfo.DeviceUuid = JLCommsg.UUID;
                            devinfo.Workmode = workmode;
                            devinfo.WorkmodeUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            bool result = dal.UpdateWorkmode(devinfo);
                            //新增日志记录
                            if (result == true)
                            {
                                //新增日志记录
                                bool res = dal.Addworkmode(devinfo);
                            }
                        }
                        //获取设置的梯控模式与实际设备端是否一致，不一致则下发梯控命令
                        ElevatorDAL ElevatorDAL = new ElevatorDAL();
                        List<ElevatorInfo> list1 = ElevatorDAL.QueryElevatorInf(list[0].ElevatorID);
                        if (list1.Count > 0)
                        {
                            if (list1[0].Workmode != workmode)
                            {
                                ElevatorInfo JLdata = new ElevatorInfo();
                                ApplyJLBUS BUS = new ApplyJLBUS();
                                JLdata.ID = list1[0].ID;
                                JLdata.Workmode = list1[0].Workmode;
                                if (sendtime == 2)
                                {
                                    Wait(20000);
                                    sendtime = 0;
                                }
                                else
                                {
                                    LogHelper.Log("模式不一致" + JsonConvert.SerializeObject(JLdata));

                                    BUS.LiftModeCMD(JLdata);
                                    sendtime++;
                                }

                            }
                        }
                    }
                }
                else if (tmp[3] == 17)//认证成功后电梯控制反馈
                {
                    //int projectid = tmp[tmp.Length - 6];
                    //string uuid = ComData.Substring(ComData.Length - 10, 6);
                    ResponseMessage message = new ResponseMessage();
                    message = InsertLadderRecord(JLCommsg.UUID, ComData.Substring(ComData.Length - 16, 8));
                }
            }
            catch (Exception e)
            {

            }

            //2、梯控模式开关反馈
            //3、认证成功后电梯控制反馈
        }

        public bool Wait(int second)
        {
            try
            {
                DateTime startTime = DateTime.Now;
                while (true)
                {
                    TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks);
                    if (secondSpan.TotalMilliseconds > second)
                    {
                        break;
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        public ResponseMessage InsertLadderRecord(string Device_UUID, string Owner_UUID)
        {
            ResponseMessage message = new ResponseMessage();
            RecordBUS BUS = new RecordBUS();
            try
            {
                message = BUS.InsertLadder(Device_UUID, Owner_UUID);
                if (message.errcode == 0)
                {
                    message = BUS.DeleteLadder(Device_UUID);
                }
            }
            catch (Exception e)
            {
                DataClearBUS dataClearBUS = new DataClearBUS();
                ErrorLog errorLog = new ErrorLog();
                errorLog.ErrorMsg = e.ToString();
                errorLog.Operation = "新增梯控返回结果";
                dataClearBUS.AddErrorLog(errorLog);
                message.errcode = 1;
                message.errmsg = "新增梯控返回结果异常";
                message.data = null;
                message.total = 0;
            }
            return message;
        }
        public string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task<string> t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }
        /// <summary>
        /// 门禁UI显示
        /// </summary>
        /// <param name="JLdata"></param>
        /// <param name="devip"></param>
        /// <returns></returns>
        public bool SetDoorUI(JLNonstandardResponse JLdata, string devip, string name)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                JLDoorUIResponse JLDoorUIResponse = new JLDoorUIResponse();
                JLDoorUIData JLDoorUIData = new JLDoorUIData();
                JLDoorUIResponse.Name = "setDoorUIRequest";// "customRequest";
                JLDoorUIResponse.UUID = JLdata.UUID;// "umph52vvm5mu";
                JLDoorUIResponse.TimeStamp = JLdata.TimeStamp;// 111111;
                JLDoorUIResponse.Session = JLdata.Session;// "umph52vvm5mu_1234567890";
                JLDoorUIData.NameEnabled = 1;
                JLDoorUIData.PictureEnabled = 0;
                JLDoorUIData.Name = name;
                JLDoorUIData.Picture = "";
                JLDoorUIResponse.Data = JLDoorUIData;
                string re = HttpClientPost("http://" + devip + ":8011/Request", JLDoorUIResponse);
                JLNonstandardReturn JLNonstandardReturn = JsonConvert.DeserializeObject<JLNonstandardReturn>(re);
                if (JLNonstandardReturn.Code == 1)
                {

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                return false;
            }
            //return message;
        }
        public int GetTimeStamp()
        {
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }
    }

}
